package pk.nak.responses;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import pk.nak.data.EatOut;
import pk.nak.data.EatOutCollection;
import pk.nak.utils.XMLUtils;

public class NearestEatOutsResponse extends BaseResponse {
	private EatOutCollection eatouts;
	@Override
	public void onSuccess(String response) {
		try{
			this.response = response;
			DocumentBuilderFactory dbfLoginResponse = DocumentBuilderFactory.newInstance();
	        DocumentBuilder dbLoginResponse = dbfLoginResponse.newDocumentBuilder();
	        
	        Document dom = dbLoginResponse.parse(new InputSource(new StringReader(response)));
	        NodeList nl = dom.getElementsByTagName("eatout");
	        
	        this.eatouts = new EatOutCollection();
	        
	        if ( nl != null && nl.getLength() > 0 ){
	        	for ( int i = 0 ; i < nl.getLength(); i ++){
	        		Element ele = (Element)nl.item(i);

	        		String eatoutid = XMLUtils.getTextValue(ele, "eatoutid");
	        		String eatoutname = XMLUtils.getTextValue(ele, "title");
	        		String eatoutaddress = XMLUtils.getTextValue(ele, "address");
	        		String eatouthalal = XMLUtils.getTextValue(ele, "halal");//XMLUtils.getTextValue(ele, "phone");
	        		String eatoutdescription = XMLUtils.getTextValue(ele, "description");//XMLUtils.getTextValue(ele, "rating");
	        		String eatoutmap = "";//XMLUtils.getTextValue(ele, "map");
	        		String eatoutlogo = XMLUtils.getTextValue(ele, "logo");//XMLUtils.getTextValue(ele, "logo");
	        		String eatoutdisstr = XMLUtils.getTextValue(ele, "distance");
	        		String eatouttype = XMLUtils.getTextValue(ele, "typename");
	        		double eatoutlat = Double.parseDouble(XMLUtils.getTextValue(ele, "latitude"));
	        		double eatoutlng = Double.parseDouble(XMLUtils.getTextValue(ele, "longitude")); 
	        		double eatoutdistance = eatoutdisstr.compareTo("")== 0 ? 0.0 : Double.parseDouble(eatoutdisstr);
	        		
	        		this.eatouts.addEatOut(
	        				new EatOut(eatoutid, eatoutname, eatouttype, 
	        						eatoutaddress, eatouthalal, 
	        						eatoutdescription, eatoutmap, 
	        						eatoutlogo, eatoutdistance,eatoutlat,eatoutlng)
	        				);
	        	}
	        }
		}catch(Exception ex){
			System.out.println("-----EXP--------" + ex.getMessage());
		}
	}
	public EatOutCollection getEatouts() {
		return eatouts;
	}
}
